/*
 * MIT License
 *
 * Copyright (c) 2019 Cheng.Wei
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package tk.jfree.summer.excel.reflection;

import tk.jfree.summer.excel.ColumnConversion;
import tk.jfree.summer.excel.annotation.Column;
import tk.jfree.summer.excel.annotation.Table;
import tk.jfree.summer.excel.exception.ExcelException;
import tk.jfree.summer.excel.metadata.Excel;
import tk.jfree.summer.excel.metadata.ExcelField;
import tk.jfree.summer.excel.type.TypeHandler;
import tk.jfree.summer.excel.type.TypeHandlerRegistry;
import tk.jfree.summer.excel.type.UnknownTypeHandler;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Cheng.Wei
 */
public class Reflector {
    private Reflector(){}
    /**excel表列信息*/
    private static final Map<Class<?>, Excel> SHEET_INFO = new ConcurrentHashMap<>();

    public static Excel sheet(Class<?> clazz){
        SHEET_INFO.computeIfAbsent(clazz,
                k-> {
                    Excel excel = new Excel();
                    excel.setExcelType(clazz);
                    Table table = Optional.ofNullable(clazz.getAnnotation(Table.class))
                            .orElseThrow(()->new ExcelException(clazz+"缺少tk.jfree.summer.excel.annotation.Table注解"));
                    excel.setSheet(table.sheet());
                    excel.setFirst(table.first());
                    List<ExcelField> excelFields = Stream.of(clazz.getDeclaredFields())
                            .filter(field -> Optional.ofNullable(field.getAnnotation(Column.class)).isPresent())
                            .map(field-> {
                                field.setAccessible(true);
                                Column column = field.getAnnotation(Column.class);
                                ExcelField excelFile = new ExcelField();
                                excelFile.setField(field);
                                excelFile.setNotes(column.notes());
                                excelFile.setProperty(field.getName());
                                excelFile.setColumn(column.name());
                                excelFile.setIndex(ColumnConversion.getIndex(field.getAnnotation(Column.class).name()));
                                excelFile.setFormat(column.format());
                                excelFile.setWidth(column.width()*256);
                                excelFile.setTypeHandler(init(field));
                                return excelFile; }).collect(Collectors.toList());
                    excel.setResultMap(excelFields);
                    return excel;
        });
        return SHEET_INFO.get(clazz);
    }


    public static TypeHandler init(Field field){
        try {
            Class<? extends TypeHandler<?>> fieldClazz = field.getAnnotation(Column.class).typeHandler();
            if(!fieldClazz.isAssignableFrom(UnknownTypeHandler.class)){
                return fieldClazz.getConstructor(Field.class).newInstance(field);
            }
            TypeHandler<?> typeHandler = new TypeHandlerRegistry(field).getTypeHandler(field.getType());
            return Optional.ofNullable(typeHandler)
                    .orElseThrow(()->
                            new ExcelException(String.format("找不到%s#%s 的typeHandler 对象",
                                    field.getDeclaringClass().getName(), field.getName())));
        } catch (NoSuchMethodException| SecurityException| InstantiationException| IllegalAccessException|
                IllegalArgumentException| InvocationTargetException e) {
            throw new ExcelException("对象解析失败...", e);
        }

    }
}
